<template>
  <div :class="$style.wrap">
    <Button type="primary" @click="clickHandle">{{ text }}</Button>
    <el-dialog :visible.sync="visible" title="新建评分表" :close-on-click-modal="false" @open="initFormData" @closed="closedHandle">
      <FormContainer :column="1">
        <el-form ref="form" :model="formData" :rules="formRules" label-width="80px">
          <el-form-item prop="title" label="评分表名称">
            <el-input v-model="formData.title" maxlength="100" type="textarea" :autosize="{minRows:1}" tip placeholder="请输入评分表名称" clearable></el-input>
          </el-form-item>
          <el-form-item>
            <div class="button-container" style="padding-top:0">
              <Button @click="visible=false">取消</Button>
              <Button type="primary" @click="confirmHandle">确定</Button>
            </div>
          </el-form-item>
        </el-form>
      </FormContainer>
    </el-dialog>
  </div>
</template>
<script>
import FormContainer from '@/components/FormContainer'
import { questionnaireAddGetId, questionnaireUpdate } from '@/api/questionnaire'
import { deepCopy } from '@/utils'
export default {
  name: 'PSQTitle',
  components: {
    FormContainer
  },
  props: {
    selectionList: {
      type: Array,
      default: () => []
    },
    text: {
      type: String,
      default: '新增'
    },
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      visible: false,
      formData: {
        title: '',
        questionnaireSort: 1,
        state: 0
      },
      formRules: {
        title: [{ required: true, message: '请输入评分表名称', trigger: 'change' }]
      }
    }
  },
  methods: {
    clickHandle() {
      if (!this.isEdit) {
        this.visible = true
      } else {
        return this.$checkSelected(this.selectionList).then(() => {
          const state = this.selectionList[0].state
          if (state === '1' || state === 1) {
            this.$message.warning('评分表已发布，不能编辑！')
          } else {
            this.visible = true
          }
        })
      }
    },
    confirmHandle() {
      return this.$refs.form.validate().then(() => {
        const data = deepCopy(this.formData)
        const ajax = this.isEdit ? (data.id = this.selectionList[0].id, questionnaireUpdate) : questionnaireAddGetId
        return ajax(data).then(res => {
          this.$emit('on-success', this.isEdit ? data.id : res.msg)
          this.visible = false
        })
      })
    },
    closedHandle() {
      this.resetFields()
    },
    resetFields() {
      this.$refs.form.resetFields()
    },
    initFormData() {
      if (this.isEdit) {
        for (const k of Object.keys(this.formData)) {
          this.$set(this.formData, k, this.selectionList[0][k])
        }
      }
    }
  }
}
</script>
<style lang='scss' module>
.wrap{
    display: inline-block;
}
</style>
